/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.apt.ServletClient;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apt.Bean.MemberEnties;
import org.apt.connectDB.MahoaPassword;
import com.myapp.DAO.MemberDao;

/**
 *
 * @author Administrator
 */
public class editMember extends HttpServlet {

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();


        MemberEnties mber;

        String random = MahoaPassword.getRandomString(20);
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        List items = null;
        try {
            items = upload.parseRequest(request);
        } catch (FileUploadException e) {
            e.printStackTrace();
        }
        Iterator itr = items.iterator();
        Hashtable params = new Hashtable();
        String filename = null;
        String imageName = "";
        HttpSession session = request.getSession(true);
        MemberEnties mberold = MemberDao.getMemberByUserName(session.getAttribute("UserID").toString());
        while (itr.hasNext()) {
            FileItem item = (FileItem) itr.next();
            if (item.isFormField()) {
                params.put(item.getFieldName(), item.getString());
            } else {
                try {
                    String realPath = "";
                    String itemName = item.getName();
                    filename = itemName.substring(itemName.lastIndexOf("\\") + 1);

                    if (filename == "") {
                        imageName = mberold.getTxtImage();
                    } else {
                        imageName = random + "-" + filename;
                        realPath = getServletContext().getRealPath("/") + "images/imagemember\\" + random + "-" + filename;
                        File saveFile = new File(realPath);
                        item.write(saveFile);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

                String username = (String) params.get("txtUserName");
                String fullname = (String) params.get("txtFullName");
                String Image = imageName;
                String Email = (String) params.get("txtEmail");
                String birthdayold = (String) params.get("txtBirthdayold");
                String birthdaynew = (String) params.get("txtBirthday");
                String birthday = "";
                if (birthdaynew.equals("")) {
                    birthday = birthdayold;
                } else {
                    birthday = birthdaynew;
                }
                String idcard = (String) params.get("txtIDCard");
                String mobilephone = (String) params.get("txtMobile");
                String homephone = (String) params.get("txtHomePhone");
                String address = (String) params.get("txtAddress");
                boolean gender;
                String getgender = (String) params.get("gender");
                if (getgender.equalsIgnoreCase("0")) {
                    gender = false;
                } else {
                    gender = true;
                }
                mber = new MemberEnties();
                mber.setTxtUserName(username);
                mber.setTxtFullName(fullname);
                mber.setTxtImage(Image);
                mber.setTxtEmail(Email);
                mber.setTxtBirthday(birthday);
                mber.setTxtIDCard(idcard);
                mber.setTxtMobile(mobilephone);
                mber.setTxtHomePhone(homephone);
                mber.setTxtAddress(address);
                mber.setTxtgender(gender);

                boolean userexit = MemberDao.checkExistUser(username);
                if (!userexit) {
                    out.print("<script>alert('The user name is not existed  !');window.location.href='MemberEdit.jsp';</script>");
                } else {
                    if (MemberDao.EditMemberB(mber)) {
                        //HttpSession session = request.getSession(true);
                        session.setAttribute("member", mber);
                        out.print("<script>alert('Update information success!');window.location.href='Member.jsp';</script>");
                    } else {
                        out.print("<script>alert('Update information fail, please try a gain!');window.location.href='MemberEdit.jsp';</script>");
                    }
                    try {
                    } catch (Exception ex) {
                        ex.printStackTrace();
                        System.out.println("Error:" + ex.getMessage() + "");
                    } finally {
                        out.close();
                    }
                }
            }
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
